from utils import Namespace
import cards
import location
import ConfigParser
import datetime

class Config:

    def __init__(self,configFileName):
        parser=ConfigParser.ConfigParser()
        parser.readfp(open(configFileName))

        self._parser=parser
        
        for methodName in dir(self):
            if not methodName.startswith('parse') or methodName=="parseOther":
                continue

            method=getattr(self,methodName)
            if not callable(method):
                pass

            method()

        self.parseOther()

    def set_(self,name,updateDict=None):
        updateDict=updateDict or {}
        if 'parser' in updateDict:
            del updateDict['parser']
        if 'self' in updateDict:
            del updateDict['self']

        parser=self._parser

        _dict=dict(parser.items(name))
        _dict.update(updateDict)

        setattr(self,name,Namespace(**_dict))

    def parseCard(self):
        parser=self._parser

        cardList=[(int(code),self.findCard(cardName)) for code,cardName in parser.items("cards")]
        cardList.sort()
        cardList=[card for code,card in cardList]
        self.cardList=cardList

        parser.remove_section("cards")

    def parseCardRate(self):
        parser=self._parser

        cardRate=[(int(code),float(prob)) for code,prob in parser.items("cardRate")]
        self.cardRate=cardRate

        parser.remove_section("cardRate")

    def parseCardPrice(self):
        parser=self._parser

        cardPrice=[(int(code),int(price)) for code,price in parser.items("cardPrice")]
        self.cardPrice=cardPrice

        parser.remove_section("cardPrice")

    def parseData(self):
        parser=self._parser

        interest=float(parser.get("data","interest"))
        bonus=tuple([int(x) for x in parser.get("data","bonus").split(',')])
        charity=tuple([int(x) for x in parser.get("data","charity").split(',')])
        pointsFree=tuple([int(x) for x in parser.get("data","pointsFree").split(',')])
        estatePrice=tuple([int(x) for x in parser.get("data","estatePrice").split(',')])
        initLotterySum=int(parser.get("data","initLotterySum"))
        lotteryCost=int(parser.get("data","lotteryCost"))
        initCash=int(parser.get("data","initCash"))
        barrierRange=int(parser.get("data","barrierRange"))
        levelMax=int(parser.get("data","levelMax"))

        self.set_("data",locals())
        parser.remove_section("data")

    def parseCharMap(self):
        parser=self._parser

        self.charMap={}
        self.mapChar={}

        for char,loc in parser.items("mapChar"):
            char=char.upper()

            if loc=="Start":
                self.startChar=char

            if loc.endswith("Estate"):
                loctype=location.Estate
            else:
                loctype=getattr(location,loc,None)

            self.mapChar[char]=loctype
            self.charMap[loc]=char

        parser.remove_section("mapChar")

    def parseDate(self):
        parser=self._parser

        initDate=datetime.datetime.strptime(parser.get("date","initDate"),"%Y.%m.%d")
        endDate=datetime.datetime.strptime(parser.get("date","endDate"),"%Y.%m.%d")
        roundTime=datetime.timedelta(int(parser.get("date","roundTime")))

        self.set_("date",locals())
        parser.remove_section("date")

    def parseOther(self):
        parser=self._parser

        for section in parser.sections():
            self.set_(section)

            parser.remove_section(section)

    def parseNews(self):
        parser=self._parser

        self.news=Namespace(newsTitle=parser.get("news","newsTitle").split('|'))

        parser.remove_section("news")

    def findCard(self,cardName):
        return getattr(cards,cardName,None)
